<template>
  <div class="common-prop-scroll">
    <el-form label-position="top" class="common-prop-container">
      <el-form-item label="字段名宽度（单位：px）">
        <el-input-number
          v-model="widgetData.config.labelWidth"
          :min="0"
          :max="200"
          :step="10"
          size="small"
          controls-position="right"
          class="input-number"
          @change="changeData"
        />
      </el-form-item>
      <el-form-item label="表单提交校验">
        <!-- <div slot="label" class="label-name">表单提交校验 ></div> -->
        <Validate v-model="widgetData.config.formValidate" :field-list="fieldList" :type="1" @freshData="initFieldList" />
      </el-form-item>
      <el-form-item label="组件显示条件">
        <!-- <div slot="label" class="label-name">组件显示条件 ></div> -->
        <Validate v-model="widgetData.config.fieldCondition" :all-field-list="allFieldList" :field-list="fieldList" :key-to-name="allKeyToName" :type="2" @freshData="initFieldList" />
      </el-form-item>
      <el-form-item label="字段名显示位置">
        <el-radio-group v-model="widgetData.config.labelPosition">
          <el-radio class="fb-radio" label="right"><span :class="{'active': widgetData.config.labelPosition === 'right'}" class="label-name">左右结构</span></el-radio>
          <el-radio class="fb-radio" label="top"><span :class="{'active': widgetData.config.labelPosition === 'top'}" class="label-name">上下结构</span></el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Validate from './commonValidate';
import { forEachFormOptions } from '@/utils/formMakeUtils.js';
import { EventBus } from '@/utils/eventBus';
export default {
  components: { Validate },
  props: {
    widgetData: {
      type: Object,
      default: () => {
        return {
          list: [],
          config: {
            labelWidth: 100, labelPosition: 'right',
            formValidate: [], // 发起审批验证
            fieldCondition: [] // 字段显示条件
          }
        };
      }
    },
    fixedId: {
      type: String | Number,
      default: ''
    }
  },
  data() {
    return {
      fieldList: [], // 不包含子表单那字段
      allFieldList: [], // 所有组件（除栅格布局组件外）、子表单内字段、栅格布局内字段
      keyToName: null,
      allKeyToName: null
    };
  },
  created() {
    EventBus.$on('formOptionsChange', configObj => {
      if (configObj.type.indexOf('remove') >= 0) {
        this.initFieldList();
      }
    });
    EventBus.$on('changeLinkForm', configObj => {
      this.initFieldList();
    });
    EventBus.$on('subformStatisticsChange', configObj => {
      this.initFieldList();
    });
    EventBus.$on('freshFieldList', () => {
      this.initFieldList();
    });
    EventBus.$on('inputDataTypeChange', ({ element }) => {
      this.inputDataTypeChange(element);
    });
  },
  methods: {
    initFieldList() {
      const fieldList = [];
      const allFieldList = [];
      const keyToName = new Map();
      const allKeyToName = new Map();
      const currentFixedId = `formId_${this.fixedId}`;
      forEachFormOptions(this.widgetData.list, (element) => {
        element.showName = element.name;
        if (!['grid', 'titleExplain', 'title', 'createTime', 'createUser', 'workflowId'].includes(element.type)) {
          fieldList.push(element);
          keyToName.set(element.key, element.showName);
        }
        if (element.type !== 'grid') {
          allKeyToName.set(element.key, element.showName);
          allFieldList.push(element);
        }
        if (element.type === 'subform') {
          element.subform.forEach(subformElement => {
            subformElement.showName = `${element.name}.${subformElement.name}`;
            if (element.options.statistics && element.options.statistics.length && element.options.statistics.includes(subformElement.key)) {
              fieldList.push(subformElement);
              keyToName.set(subformElement.key, subformElement.showName);
            }
            allFieldList.push(subformElement);
            allKeyToName.set(subformElement.key, subformElement.showName);
          });
        }
        /**
         * 需要排除关联自己的关联表单
         */
        if (element.type === 'linkForm' && element.options.isStatistics && element.options.statistics.length && element.options.remoteParams.id !== currentFixedId) {
          element.subform.forEach(linkElement => {
            linkElement.showName = `${element.name}.${linkElement.name}`;
            if (element.options.statistics.includes(linkElement.key)) {
              fieldList.push(linkElement);
              keyToName.set(linkElement.key, linkElement.showName);
            }
          });
        }
      }, { notForEachSubform: true });
      this.fieldList = fieldList;
      this.allFieldList = allFieldList;
      this.keyToName = keyToName;
      this.allKeyToName = allKeyToName;
      this.hadnelFieldListChange();
    },
    changeData() {
      this.$emit('changeData');
    },
    // 去除 表单提交校验 和 组件显示条件 中已经不存在的字段
    hadnelFieldListChange() {
      const formValidate = this.widgetData.config.formValidate;
      let fieldCondition = this.widgetData.config.fieldCondition;
      if (formValidate && formValidate.length) {
        formValidate.forEach(i => {
          this.fixedFilterList(i);
          this.fixedFilterList(i, 'frontFilterList');
        });
      }
      if (fieldCondition && fieldCondition.length) {
        fieldCondition.forEach(i => {
          if (!i.filterListGroup) i.filterListGroup = [];
          // 兼容旧数据
          if (i.filterList && i.filterList.length && i.filterListGroup.length === 0) {
            i.filterListGroup = [{
              filterList: i.filterList,
              role: i.role
            }];
            delete i.role;
            delete i.filterList;
          }
          i.fieldList = i.fieldList.filter(j => {
            return this.allKeyToName.has(j) || j.filterField === 'status';// 状态字段非表单组件，单独处理
          });
          i.filterListGroup = i.filterListGroup.filter(group => {
            this.fixedFilterList(group);
            return group.filterList.length;
          });
        });
        fieldCondition = fieldCondition.filter(i => i.fieldList.length > 0);
        this.$set(this.widgetData.config, 'fieldCondition', fieldCondition);
      }
    },
    // 验证字段是否还存在，不存在则删除该条规则
    fixedFilterList(i, key = 'filterList') {
      const keyToName = this.keyToName;
      if (i[key] && i[key].length) {
        i[key] = i[key].filter(j => {
          if (j.valueType === 1 && j.value && !keyToName.has(j.value)) {
            this.$set(j, 'value', '');
          }
          if (!keyToName.has(j.filterField) && j.filterField !== 'status') { // 状态字段非表单组件，单独处理
            return false;
          }
          return true;
        });
      }
    },
    inputDataTypeChange(element) {
      const keys = ['formValidate', 'fieldCondition'];
      // input 字段修改 dataType 时，初始化筛选条件中的 math 和 value
      keys.forEach(key => {
        if (this.widgetData.config[key]) {
          this.widgetData.config[key].forEach(i => {
            if (i.filterList && i.filterList.length) {
              i.filterList.forEach(j => {
                if (element.key === j.filterField) {
                  this.$set(j, 'value', '');
                  this.$set(j, 'math', '=');
                }
              });
            }
            if (i.frontFilterList && i.frontFilterList.length) {
              i.frontFilterList.forEach(j => {
                if (element.key === j.filterField) {
                  this.$set(j, 'value', '');
                  this.$set(j, 'math', '=');
                }
              });
            }
          });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.input-number {
  width: 240px;
  &::v-deep {
    .el-input__inner {
      padding-left: 8px;
      text-align: left;
    }
    .el-input-number__increase,.el-input-number__decrease {
      background: #fff;
    }
  }
}
.common-prop-container {
  &::v-deep {
    .el-form-item {
      padding-right: 5px;
    }
    .el-form-item__label {
      padding: 0;
    }
  }
}
.label-name {
  color: #333;
  font-size: 14px;
  &.active {
    font-weight: bold;
  }
}
.common-prop-scroll {
  height: 100%;
  @include scrollBar();
}
</style>
